/*
 * Copyright 2011 es-planning Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package jp.arctos.ursus.extension.net.testutil;

import java.io.IOException;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.DatagramChannel;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;

public class SimpleDatagramEchoServer {
    private DatagramChannel channel;
    private boolean isClosed;

    public SimpleDatagramEchoServer(SocketAddress localAddress) throws IOException {
        channel = DatagramChannel.open();
        channel.configureBlocking(true);
        channel.socket().setReuseAddress(true);
        channel.socket().bind(localAddress);
        receive();
    }

    private void receive() {
        ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
        executor.submit(new EchoServerRunnable());
    }

    public void close() {
        isClosed = true;
        try {
            channel.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    class EchoServerRunnable implements Runnable {
        public void run() {
            try {
                for (; !isClosed;) {
                    ByteBuffer buffer = ByteBuffer.allocate(1024);
                    SocketAddress remoteAddress = channel.receive(buffer);
                    if (remoteAddress != null) {
                        buffer.flip();
                        String str = decode(buffer);
                        ByteBuffer retBuffer = pack(encode(str));
                        send(retBuffer, remoteAddress);
                    }
                }
            } catch (IOException e) {
            }
        }

        protected void send(ByteBuffer buffer, SocketAddress remoteAddress) throws IOException {
            channel.send(buffer, remoteAddress);
        }

        protected String decode(ByteBuffer buffer) {
            byte[] bytes = new byte[buffer.remaining()];
            buffer.get(bytes);
            return new String(bytes);
        }

        protected byte[] encode(String str) {
            return (str + "-server").getBytes();
        }

        protected ByteBuffer pack(byte[] bytes) {
            ByteBuffer buffer = ByteBuffer.allocate(bytes.length);
            buffer.put(bytes);
            buffer.flip();
            return buffer;
        }
    }
}
